/**
 * 上传组件初始化js
 */
var upload_token = false;
var typeNormal = 'normal'
    ,typeAvatar = 'avatar'
;

/**
 * 积分入学jsonp返回时调用方法
 * @param json
 */
function callback(json) {
}

function funShow(dom){
}

function funShowYb(url) {
    var gallery='<div class="weui-gallery" id="ybdiv" style="display: block">'+
        '<span class="weui-gallery__img" style="background-image: url('+url+');"></span>'+
        '<div class="weui-gallery__opr">'+
        '<a href="javascript:deleteYb()" class="weui-gallery__del" style="color: #ffffff;font-size: 16px;">'+
        '<i class="weui-icon-delete weui-icon_gallery-delete"></i>&nbsp;&nbsp;关闭'+
        '</a>'+
        ' </div>'+
        ' </div>';
    $("body").append(gallery);
}
function deleteYb() {
    $("#ybdiv").remove();
}
$(function(){
    // 允许上传的图片类型
    var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'];
    // 1024KB * 5，也就是 5MB
    var maxSize = 1024 * 1024 * 20 ;
    // 图片最大宽度
    var maxWidth = 300;
    // 最大上传图片数量
    var maxCount = 6;
    $(document).delegate('.js_file', 'change', function(event) {
        var config = $(this).parents('[data-role="upload"]').data('content');
        if(!config.type){
            config.type = typeNormal;
        }
        if('string' == typeof config){
            config = JSON.parse(config);
        }
        var files = event.target.files
            ,$dom = $(this).parents('.weui-uploader__bd:first')
        ;
        // 如果没有选中文件，直接返回
        if (files.length === 0) {
            return;
        }

        for (var i = 0, len = files.length; i < len; i++) {
            var file = files[i];
            var reader = new FileReader();
            // 如果类型不在允许的类型范围内
            if (allowTypes.indexOf(file.type) === -1) {
                $.alert('该类型不允许上传', '警告');
                continue;
            }

            if (file.size > maxSize) {
                $.alert('图片太大，不允许上传', '警告');
                continue;
            }

            if ($('.weui_uploader_file').length >= maxCount) {
                $.alert('最多只能上传' + maxCount + '张图片', '警告');
                return;
            }

            reader.onload = function(e) {
                var img = new Image();
                img.onload = function() {
                    // 不要超出最大宽度
                    var w = Math.min(maxWidth, img.width);
                    // 高度按比例计算
                    var h = img.height * (w / img.width);
                    var canvas = document.createElement('canvas');
                    var ctx = canvas.getContext('2d');
                    // 设置 canvas 的宽度和高度
                    canvas.width = w;
                    canvas.height = h;
                    ctx.drawImage(img, 0, 0, w, h);
                    var base64 = canvas.toDataURL('image/png');

                    // 插入到预览区
                    var $preview = $('<li class="weui-uploader__file weui-uploader__file_status" onclick="funShow(this)" style="background-image:url(' + base64 + ')"><div class="weui-uploader__file-content">0%</div></li>');
                    $dom.find('.weui-uploader__files').prepend($preview);
                    var num = $('.weui_uploader_file').length;
                    $('.js_counter').text(num + '/' + maxCount);

                    // 然后假装在上传，可以post base64格式，也可以构造blob对象上传，也可以用微信JSSDK上传
                    var url = getRootPath()+'/wfw/spyxmp/file/upload';
                    var formData = new FormData();
                    formData.append('file', file);
                    formData.append('fileSize', file.size);
                    formData.append('openId', $('#openId').val())
                    if(config.params){
                        for(var item in config.params){
                            formData.append(item, config.params[item]);
                            console.log(item+"======"+ config.params[item]);
                        }
                    }
                    //组建XMLHttpRequest 上传文件
                    var request = new XMLHttpRequest();
                    request.addEventListener('progress', function(evt){
                        if(evt.lengthComputable){
                            var percent = evt.loaded /evt.total * 100;
                            $preview.find('.weui-uploader__file-content').text(percent + '%');
                        }
                    });
                    //上传连接地址
                    request.open("POST", url, true);
                    request.onreadystatechange=function()
                    {
                        if (request.readyState==4)
                        {
                            if(request.status == 200){
                                var response = JSON.parse(request.response);
                                if(response.success){

                                    //如果type=avatar 则只能上传单个文件，清空之前的文件
                                    if(config.type == 'avatar'){
                                        $dom.find('.weui-uploader__files').find('.weui-uploader__file').not('.weui-uploader__file_status').remove();
                                    }
                                    $preview.attr('data-id', response.data.ID);
                                    $preview.removeClass('weui-uploader__file_status').find('.weui-uploader__file-content').remove();
                                    $.toptip('上传成功', 'success');
                                    $dom.parents('.upload-control:first').find('.errorTips').remove();
                                }else{
                                    $.toptip(response.msg || '上传失败，请稍后重试', 'error');
                                    $preview.remove();
                                }
                            }else{
                                $.toptip('服务连接异常，请稍后重试', 'error');
                                $preview.remove();
                            }
                        }
                    }
                    request.send(formData);

                    // var progress = 0;
                    // function uploading() {
                    //     $preview.find('.weui-uploader__file-content').text(++progress + '%');
                    //     if (progress < 100) {
                    //         setTimeout(uploading, 10);
                    //     } else {
                    //         // 如果是失败，塞一个失败图标
                    //         //$preview.find('.weui_uploader_status_content').html('<i class="weui_icon_warn"></i>');
                    //         $preview.removeClass('weui-uploader__file_status').find('.weui-uploader__file-content').remove();
                    //
                    //         $.toptip('上传成功', 'success');
                    //     }
                    // }
                    // setTimeout(uploading, 10);
                };

                img.src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    });
    var index  //第几张图片
    ;
    $(document).delegate('.weui-uploader__file', 'click', function(){
        index = $(this).index();
        $('#galleryImg').attr("style", this.getAttribute("style"));
        $('#gallery').fadeIn(100);

        $('#gallery').data('id', $(this).parents('[data-role="upload"]').attr('id'));
    }).delegate('#gallery .weui-gallery__cancel', 'click', function(){
        $('#gallery').fadeOut(100);
    }).delegate('#gallery .weui-gallery__del', 'click', function(){
        var panelId = $(this).parents('#gallery').data('id');
        var $dom = $('#'+panelId).find('.weui-uploader__files').find("li").eq(index);
        $.confirm("确认删除该材料照片?", "确认删除?", function() {
            $('#gallery').fadeOut(100);
            var url = getRootPath()+'/wfw/spyxmp/file/del';
            $.ajax({
                url: url,
                data: {id: $dom.attr('data-id')},
                dataType: 'JSON',
                contentType: "application/x-www-form-urlencoded;charset=UTF-8",
                success: function(result, textStatus, XMLHttpRequest) {
                    if(result.success) {
                        $dom.remove();
                        $.toptip('操作成功', 'success');
                    } else {
                        $.toptip(result.msg || '操作失败', 'error');
                    }
                }
            });
        }, function() {
            //取消操作
        });
    });

    function init(id){
        if($('[data-role="upload"]').length > 0 && $('#gallery').length == 0){
            var gallery = '<div class="weui-gallery" id="gallery"><span class="weui-gallery__img" id="galleryImg"></span>'
                + '<div class="weui-gallery__opr"><a href="javascript:" class="weui-gallery__del operDom" style="color: white;font-size: 20px;">'
                + '<i class="weui-icon-delete weui-icon_gallery-delete"></i>&nbsp;删除</a>'
                + '<a href="javascript:" class="weui-gallery__cancel" style="color: white">'
                + '关闭</a>'
                +'</div></div>';
            $('body').append(gallery);
        }

        $('[data-role="upload"]').each(function(){
            var config = $(this).data('content');
            if(!config.type){
                config.type = typeNormal;
            }
            if('string' == typeof config){
                config = JSON.parse(config);
            }
            if(id){
                config.params.itemId = id;
            }
            var panelId = Math.random() + '';
            $(this).attr('data-content', JSON.stringify(config)).attr('id', panelId.substr(2, panelId.length)).addClass("upload-control");
            var pcss = {},css = {};

            //样表
            if(config.yburl!=null&&config.yburl.length>1){
                $labelDiv.append("<a href='javascript:void(0)' onclick='funShowYb(\""+config.yburl+"\")' style='float: right;color: #007aff;'>查看样表</a>");
            }
            var $panel = $('<div></div>').addClass('weui-cells');

            var $panel_cell = $('<div></div>').addClass('weui-cell');

            var $uploader = $('<div></div>').addClass('weui-uploader');

            var $header = $('<div></div>').addClass('weui-uploader__hd');

            var $labelDiv = $('<div></div>').addClass('weui-uploader__title').append(
                config.label ? config.label : '上传文件'
            );

            var $body = $('<div></div>').addClass('weui-uploader__bd');

            var $btn_div = $('<div></div>').addClass('weui-uploader__input-box').css({'display': 'inline-block'});
            //正常上传
            if(typeNormal == config.type){

            }else if(typeAvatar == config.type){
                $labelDiv.css({'font-size': '15px', 'text-align': 'center'});
                $panel.css({'text-align': 'center'});
                $body.css({'margin': '0px auto'});
                $btn_div.css({'float': 'none'});
            }

            var $btn = $('<input />', {'type': 'file', 'accept': 'image/*', 'multiple': ''})
                .addClass('weui-uploader__input js_file operDom').data('config', config);

            $body.append($btn_div.append($btn));

            //查找有没有数据，直接添加到页面
            funInitFilefn({dom: $body, config: config});
            $header.append($labelDiv);
            $panel.append($panel_cell.append($uploader.append($header).append($body)));
            if(typeAvatar == config.type){
                $(this).empty().append($panel);
            }else{
                $(this).empty().append($panel);
            }

        });
    }

    function funInitFilefn(cfg){
        var url = getRootPath() + '/wfw/spyxmp/file/query';
        $(cfg.dom).find(".weui-uploader__files").remove();
        var $wfiles = $('<ul></ul>').addClass('weui-uploader__files').css({'display': 'inline-block'});
        if(typeAvatar == cfg.config.type){

        }else{
            $wfiles.css({'display': 'inline-block', 'float': 'left'})
        }
        $(cfg.dom).prepend($wfiles);
        cfg.config.params.openId = $('#openId').val();
        $.ajax({
            url: url,
            data: cfg.config.params,
            async : false,
            contentType: "application/x-www-form-urlencoded;charset=UTF-8",
            success: function(response, textStatus, XMLHttpRequest){
                if(response.success) {
                    if(response.data.length > 0){
                        for ( var i = 0; i < response.data.length; i++) {
                            var data = response.data[i];
                            cfg.data = data;
                            var previewHtml = getColorboxObjFn(cfg);
                            $(cfg.dom).find(".weui-uploader__files").prepend(previewHtml);
                        }
                    }
                }
            }
        });
    }

    function callback(json){
    }

    /**
     * 获取文件
     * @param cfg
     * @returns
     */
    function getColorboxObjFn(cfg){
        var src =getRootPath()+cfg.data.FILEPATH;
        var html = '<li class="weui-uploader__file" onclick="funShow(this)" data-id="' + cfg.data.ID + '" style="background-image: url(' + src + ')"></li>';
        return html;
    }

    init();

    funInitFileItemId = function(id){
        init(id);
    }

});

var funInitFileItemId = 0;

//取消上传事件
function canceluploadfn(cfg){
    var msgLayer = layer.msg('确认删除该材料照片？', {
        time: 20000, //20s后自动关闭
        offset: '200px',
        scrollbar:false,
        btn: ['确认', '取消'],
        yes:function(){
            var url = getRootPath()+'/wfw/spyxmp/file/del';
            $.ajax({
                url: url,
                data: cfg.data,
                dataType: 'JSON',
                contentType: "application/x-www-form-urlencoded;charset=UTF-8",
                success: function(result, textStatus, XMLHttpRequest) {
                    layer.close(loadLayer);
                    if(result.success) {
                        if(cfg.model == 'single'){
                            $(cfg.dom).parents('ul:first').find('li.upload').show();
                        }
                        $(cfg.dom).parents("li").remove();
                        layer.close(msgLayer);
                        $.toptip(result.msg, 'success');
                    } else {
                        $.toptip(result.msg || '操作失败', 'warning');
                    }
                }
            });
        }
    });
}